/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2014 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_silent.h"

#include "silent.h"
#include "server.h"

int slt_errno;
jmp_buf jumper;

/* If you declare any globals in php_silent.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(silent)
*/
int silent_running = 1;
/* True global resources - no need for thread safety here */
static int le_silent;
#define SLT_SERVER_NAME	"SERVER_SILENT"

#define USER_CALL_FUNCTION 	10
#define SLT_API_CONNECTION_FUNC	0
#define SLT_API_RCV_FUNC	1
#define SLT_API_DONE_FUNC	2

static zval *user_call_function[USER_CALL_FUNCTION];

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("silent.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_silent_globals, silent_globals)
    STD_PHP_INI_ENTRY("silent.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_silent_globals, silent_globals)
PHP_INI_END()
*/
/* }}} */

zval *php_call_rcv(int schedid, char *buff, int len)
{
	zval *retval = NULL;
	zval **params[3];
	zval *zschedid;
	zval *zbuff;
	zval *zlen;

	MAKE_STD_ZVAL(zschedid);
    ZVAL_LONG(zschedid, (long)schedid);

	MAKE_STD_ZVAL(zlen);
	ZVAL_LONG(zlen, (long)len);

	MAKE_STD_ZVAL(zbuff);
	ZVAL_STRINGL(zbuff, buff, len, 1);

	params[0] = &zschedid;
	params[1] = &zbuff;
	params[2] = &zlen;
	

	TSRMLS_FETCH_FROM_CTX(slt_ctx);

	if (call_user_function_ex(EG(function_table), NULL, user_call_function[SLT_API_RCV_FUNC], &retval, 3, params, 0, NULL TSRMLS_CC) == FAILURE)
    {
        php_error(E_WARNING, "Failed to call user interface API %s", Z_STRVAL_P(user_call_function[SLT_API_RCV_FUNC]));
    }
	zval_ptr_dtor(&zschedid);
	zval_ptr_dtor(&zbuff);
	zval_ptr_dtor(&zlen);
	zval_ptr_dtor(*params);

	return retval;
	//zval_ptr_dtor(&retval);
}

static void slt_set_callback(int key, zval *func) {
	char *function_name = NULL;

	TSRMLS_FETCH_FROM_CTX(slt_ctx);
	if (!zend_is_callable(func, 0, &function_name TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Set callback user interface %s API interface exception", function_name);
		efree(function_name);
		return ;
	}
	efree(function_name);
	zval_add_ref(&func);
	user_call_function[key] = func;
}

void php_call_connection(char *ip, int schedid) {
	zval *retval = NULL;
	zval **params[2];
	zval *zip;
	zval *zschedid;

	MAKE_STD_ZVAL(zip);
	ZVAL_STRING(zip, ip, 1);

	MAKE_STD_ZVAL(zschedid);
	ZVAL_LONG(zschedid, (long)schedid);

	params[0] = &zip;
	params[1] = &zschedid;

    TSRMLS_FETCH_FROM_CTX(slt_ctx);

    if (call_user_function_ex(EG(function_table), NULL, user_call_function[SLT_API_CONNECTION_FUNC], &retval, 2, params, 0, NULL TSRMLS_CC) == FAILURE)
    {
        php_error(E_WARNING, "Failed to call user interface API %s", Z_STRVAL_P(user_call_function[SLT_API_CONNECTION_FUNC]));
    }
	zval_ptr_dtor(&zip);
	zval_ptr_dtor(&zschedid);
    zval_ptr_dtor(&retval);
} 

zval *php_call_done(char *buff, int len) {
	zval *retval = NULL;
	zval *zbuff = NULL;
	zval *zlen = NULL;
	zval **params[2];

	MAKE_STD_ZVAL(zbuff);
	ZVAL_STRINGL(zbuff, buff, len, 1);
	
	MAKE_STD_ZVAL(zlen);
	ZVAL_LONG(zlen, (long)len);

	params[0] = &zbuff;
	params[1] = &zlen;

	TSRMLS_FETCH_FROM_CTX(slt_ctx);
	if (call_user_function_ex(EG(function_table), NULL, user_call_function[SLT_API_DONE_FUNC], &retval, 2, params, 0, NULL TSRMLS_CC) == FAILURE) {
		php_error(E_WARNING, "Failed to call user interface API %s", Z_STRVAL_P(user_call_function[SLT_API_DONE_FUNC]));
	}
	zval_ptr_dtor(&zbuff);
	zval_ptr_dtor(&zlen);

	return retval;
	//zval_ptr_dtor(&retval);
}

PHP_FUNCTION(slt_silent_run)
{
	zval *zv = NULL;
	slt_server_t *serv = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zv) == FAILURE) {
		return ;
	}

	ZEND_FETCH_RESOURCE(serv, slt_server_t *, &zv, -1 , SLT_SERVER_NAME, le_silent);

	serv->call_rcv = php_call_rcv;	
	serv->call_connection = php_call_connection;
	serv->call_done = php_call_done;

	slt_server_create(serv);
	if (setjmp(jumper) == 0) {
		slt_server_start(serv);
	}
	RETURN_NULL();
}

PHP_FUNCTION(slt_silent_handler)
{
	zval *zv = NULL;
	zval *zv_arr = NULL;
	HashTable *vht =  NULL;
	slt_server_t *serv = NULL;
	zval **element = NULL;
	HashPosition pos = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "za", &zv, &zv_arr) == FAILURE) {
		return ;
	}

	ZEND_FETCH_RESOURCE(serv, slt_server_t *, &zv, -1, SLT_SERVER_NAME, le_silent);
	vht = Z_ARRVAL_P(zv_arr);

	for (zend_hash_internal_pointer_reset_ex(vht, &pos);
             zend_hash_get_current_data_ex(vht, (void **) &element, &pos) == SUCCESS;
             zend_hash_move_forward_ex(vht, &pos)
        ) {
		if (pos->nKeyLength) {
			if (strncmp("on_conn", pos->arKey, pos->nKeyLength) == 0) {
				slt_set_callback(SLT_API_CONNECTION_FUNC, *element);
			} else if (strncmp("on_rcv", pos->arKey, pos->nKeyLength) == 0) {
				slt_set_callback(SLT_API_RCV_FUNC, *element);
			} else if (strncmp("on_done", pos->arKey, pos->nKeyLength) == 0) {
				slt_set_callback(SLT_API_DONE_FUNC, *element);
			}
		}
	}
}

PHP_FUNCTION(slt_silent_set)
{
	zval *zv = NULL;
	zval *zv_arr = NULL;
	zval **zdata = NULL;
	slt_server_t *serv = NULL;
	HashTable *vht = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &zv, &zv_arr) == FAILURE) {
		return ;
	}

	ZEND_FETCH_RESOURCE(serv, slt_server_t *, &zv, -1, SLT_SERVER_NAME, le_silent);
	vht = Z_ARRVAL_P(zv_arr);

	if (zend_hash_find(vht, ZEND_STRS("agent_num"), (void **)&zdata) == SUCCESS) {
		serv->poll_thread_num = (int)Z_LVAL_PP(zdata);
	}

	if (zend_hash_find(vht, ZEND_STRS("job_num"), (void **)&zdata) == SUCCESS) {
		serv->job_num = (int)Z_LVAL_PP(zdata);
	}

	if (zend_hash_find(vht, ZEND_STRS("backend"), (void **)&zdata) == SUCCESS) {
		serv->backend = (int)Z_LVAL_PP(zdata);
	}
}

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_silent_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(slt_silent_init)
{
	char *host = NULL;
	int host_len;
	long port;
	long mode;
	char *p = NULL;
	slt_server_t *serv = emalloc(sizeof(slt_server_t));

	bzero(serv, sizeof(slt_server_t));
	slt_server_init(serv);
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sll", &host, &host_len, &port, &mode) == FAILURE) {
		return ;
	}
	if (host_len == 0) {
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Host address cannot be empty");
		return ;
	}

	if (mode != SLT_TCP_MODE) {
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Network model setup error");
        return ;
	}
	serv->port = port;
	serv->mode = mode;
	strncpy(serv->host, host, host_len);

	TSRMLS_SET_CTX(slt_ctx);
	ZEND_REGISTER_RESOURCE(return_value, serv, le_silent);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and 
   unfold functions in source code. See the corresponding marks just before 
   function definition, where the functions purpose is also documented. Please 
   follow this convention for the convenience of others editing your code.
*/


/* {{{ php_silent_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_silent_init_globals(zend_silent_globals *silent_globals)
{
	silent_globals->global_value = 0;
	silent_globals->global_string = NULL;
}
*/
/* }}} */

static void slt_destroy_server(zend_rsrc_list_entry *rsrc TSRMLS_DC) {
	slt_server_t *serv = rsrc->ptr;
	factory_t *factory = &(serv->factory);
	int thread_num = serv->poll_thread_num;
	reactor_t *nginx_reactor;
	int i = 0;

	mq_unlink(factory->unicom.mqd_name);
	efree(factory->child_ids);
	zend_llist_destroy(&(factory->reply_sock_manage));
	munmap(factory->data_pool->init_mem, MAP_MEMSIZE);
	for (i=0; i<serv->wait_jobnum; i++) {
		factory->sync_evfd.notify(factory->sync_evfd.evfd, 1);
		sched_yield();
	}
	for (i=0; i<serv->wait_jobnum; i++) {
                pthread_join(serv->wait_jobtids[i], NULL);
        }
	close(factory->sync_evfd.evfd);
	if (serv->wait_jobtids != NULL) {
		efree(serv->wait_jobtids);
	}
	for (i=0; i<thread_num; i++) {
		if (serv->pool == NULL) {
			continue ;
		}
		pthread_join(serv->pool[i].tid, NULL);
	}
	if (serv->pool != NULL) {
		efree(serv->pool);
	}
	zend_llist_destroy(&(serv->task_list));
	efree(serv);
	zval_ptr_dtor(&user_call_function[SLT_API_CONNECTION_FUNC]);
	zval_ptr_dtor(&user_call_function[SLT_API_RCV_FUNC]);
	zval_ptr_dtor(&user_call_function[SLT_API_DONE_FUNC]);
}

PHP_FUNCTION(slt_silent_task_one)
{
	zval *zserv = NULL;
	zval *zcall = NULL;
	long interval;
	time_t now;
	slt_server_t *serv = NULL;
	task_node_t *task_node = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlz", &zserv, &interval, &zcall) == FAILURE) {
		return ;
	}

	ZEND_FETCH_RESOURCE(serv, slt_server_t *, &zserv, -1, SLT_SERVER_NAME, le_silent);

    time(&now);
	task_node = emalloc(sizeof(task_node_t));
	task_node->delaytime = interval;
	task_node->accept_time = now;
	zval_add_ref(&zcall);
	task_node->cb = zcall;
	task_node->one = 1;

	zend_llist_add_element(&(serv->task_list), task_node);
	efree(task_node);
	serv->ticktime = interval;	
}

PHP_FUNCTION(slt_silent_task)
{
	zval *zserv = NULL;
	zval *zcall = NULL;
	time_t now;
	slt_server_t *serv = NULL;
	task_node_t *task_node = NULL;
	long interval;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlz", &zserv, &interval, &zcall) == FAILURE) {
		return ;
	}

	ZEND_FETCH_RESOURCE(serv, slt_server_t *, &zserv, -1, SLT_SERVER_NAME, le_silent);

	time(&now);

	task_node = emalloc(sizeof(task_node_t));
	task_node->delaytime = interval;
	task_node->accept_time = now;
	zval_add_ref(&zcall);
	task_node->cb = zcall;
	task_node->one = 0;

	zend_llist_add_element(&(serv->task_list), task_node);
	efree(task_node);
	serv->ticktime = interval;
}


/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(silent)
{
	/* If you have INI entries, uncomment these lines 
	REGISTER_INI_ENTRIES();
	*/
	le_silent = zend_register_list_destructors_ex(slt_destroy_server, NULL, SLT_SERVER_NAME, module_number);
	REGISTER_LONG_CONSTANT("TCP_MODE", SLT_TCP_MODE, CONST_CS | CONST_PERSISTENT);
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(silent)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(silent)
{
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(silent)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(silent)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "silent support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ silent_functions[]
 *
 * Every user visible function must have an entry in silent_functions[].
 */
const zend_function_entry silent_functions[] = {
	PHP_FE(slt_silent_init,	NULL)		/* For testing, remove later. */
	PHP_FE(slt_silent_set, NULL)
	PHP_FE(slt_silent_handler, NULL)
	PHP_FE(slt_silent_run, NULL)
	PHP_FE(slt_silent_task, NULL)
	PHP_FE(slt_silent_task_one, NULL)
	PHP_FE_END	/* Must be the last line in silent_functions[] */
};
/* }}} */

/* {{{ silent_module_entry
 */
zend_module_entry silent_module_entry = {
	STANDARD_MODULE_HEADER,
	"silent",
	silent_functions,
	PHP_MINIT(silent),
	PHP_MSHUTDOWN(silent),
	PHP_RINIT(silent),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(silent),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(silent),
	PHP_SILENT_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_SILENT
ZEND_GET_MODULE(silent)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
